﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;

namespace BitmapPtr
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string path = $"{Application.StartupPath}{Path.DirectorySeparatorChar}test.png";
            if (File.Exists(path))
                TbxFile.Text = path;
        }

        private void BtnOpen_Click(object sender, EventArgs e)
        {
            string file;
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.InitialDirectory = Application.StartupPath + Path.DirectorySeparatorChar;
            dialog.Title = "请选择文件";
            dialog.Filter = "图片文件(*.jpg,*.png,*.bmp,*.tif)|*.jpg;*.png;*.bmp;*.tif";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                file = dialog.FileName;
                TbxFile.Text = file;
                BtnTest_Click(null,null);
            }
        }

        private void BtnTest_Click(object sender, EventArgs e)
        {
            if (TbxFile.Text.Length==0 || !File.Exists(TbxFile.Text))
            {
                MessageBox.Show("请先选择文件");
                return;
            }
            HiPerfTimer timer = new HiPerfTimer();
            using (Bitmap bmp = (Bitmap)Image.FromFile(TbxFile.Text))
            {
                RtbMsg.AppendText($"Bitmap文件名：{Path.GetFileName(TbxFile.Text)}，图像尺寸{bmp.Width}*{bmp.Height}，图像位数{bmp.PixelFormat}{Environment.NewLine}");
                timer.Start();
                byte[] bmpbyte = BitmapHelper.Bitmap2Byte(bmp,out int width,out int height, 
                    out int stride, out int depth,out PixelFormat pixelformat);
                timer.Stop();
                int t1 = timer.Duration;
                timer.Start();
                byte[] graybyte = BitmapHelper.Color2GrayByte(bmpbyte, width, height, stride, depth);
                timer.Stop();
                int t2 = timer.Duration;
                timer.Start();
                Bitmap graymap = BitmapHelper.ByteToBitmap(graybyte, width, height, pixelformat);
                timer.Stop();
                int t3 = timer.Duration;

                RtbMsg.AppendText($"Bitmap转彩色一维字节数组，耗时{t1}毫秒，Padding={stride - width * depth / 8}{Environment.NewLine}");
                RtbMsg.AppendText($"彩色一维数组转灰度一维数组，耗时{t2}毫秒{Environment.NewLine}");
                RtbMsg.AppendText($"灰度一维数组转Bitmap，耗时{t3}毫秒{Environment.NewLine}{Environment.NewLine}");
                RtbMsg.ScrollToCaret();
                RtbMsg.AppendText($"{Environment.NewLine}");

                Bitmap bmpclone = (Bitmap)bmp.Clone();
                PbxSrc.Image = bmpclone;
                PbxDest.Image = graymap;
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}
